package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ArticleBehaviorDto;
import com.heima.behavior.service.ApBehaviorServcie;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApBehaviorServcieImpl implements ApBehaviorServcie {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询文章行为数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
        //1.参数校验
        if (dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.获取登录用户id
        ApUser apUser = ApThreadLocalUtil.getUser();
        //表示未登录
        if (apUser == null) {
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //游客身份不能进行以下操作
        if (apUser.getId() == 0) {
            return ResponseResult.okResult(405, "游客身份禁止，需进行登录");
        }
        // 默认情况下的四种情况
        Boolean isfollow = false, iscollection = false, isunlike = false, islike = false;

        //3 查看是否关注该作者
        String follow_key = "USER_FOLLOW_" + apUser.getId();
        Boolean followFlag = stringRedisTemplate.opsForHash().hasKey(follow_key, dto.getAuthorId() + "");
        if (followFlag) {
            isfollow = true;
        }
        //4 查看是否点赞了文章
        String likes_key = "USER_LIKES_" + dto.getArticleId();
        Boolean likes_flag = stringRedisTemplate.opsForHash().hasKey(likes_key, apUser.getId() + "");
        if (likes_flag) {
            islike = true;
        }
        //5 查看是否不喜欢该文章
        String unlikes_key = "USER_UNLIKES_" + dto.getArticleId();
        Boolean unlikes_flag = stringRedisTemplate.opsForHash().hasKey(unlikes_key, apUser.getId() + "");
        if (unlikes_flag) {
            isunlike = true;
        }
        //6 查看是否收藏了文章
        String collection_key = "USER_COLLECTION_" + dto.getArticleId();
        Boolean collection_flag = stringRedisTemplate.opsForHash().hasKey(collection_key, apUser.getId() + "");
        if (collection_flag) {
            iscollection = true;
        }
        //7 返回数据
        HashMap<String,Boolean> map = new HashMap<>();
        map.put("isfollow",isfollow);
        map.put("islike",islike);
        map.put("isunlike",isunlike);
        map.put("iscollection",iscollection);
        return ResponseResult.okResult(map);
    }
}
